<template>
  <view class="detail-container">
    <view class="dish-header">
      <image :src="dishInfo.image" class="dish-image" mode="aspectFill" />
      <view class="dish-basic">
        <text class="dish-name">{{ dishInfo.name }}</text>
        <view class="dish-rating">
          <uni-rate :value="dishInfo.rating" :readonly="true" />
          <text class="rating-text">{{ dishInfo.rating.toFixed(1) }} ({{ dishInfo.favoriteCount }}人收藏)</text>
        </view>
        <view class="dish-tags">
          <text class="tag cuisine">{{ dishInfo.cuisine }}</text>
          <text class="tag taste">{{ dishInfo.taste }}</text>
          <text class="tag method">{{ dishInfo.cookingMethod }}</text>
        </view>
      </view>
    </view>

    <view class="dish-actions">
      <button class="action-btn" @click="toggleFavorite" :class="{ 'favorited': dishInfo.isFavorited }">
        {{ dishInfo.isFavorited ? '已收藏' : '收藏' }}
      </button>
      <button class="action-btn primary" @click="addToNutrition">加入营养规划</button>
      <button class="action-btn" @click="showRateModal" :class="{ 'rated': userRating > 0 }">
        {{ userRating > 0 ? `已评分(${userRating}分)` : '评分' }}
      </button>
      <button class="action-btn" @click="testStatus" style="font-size: 20rpx;">测试状态</button>
    </view>

    <view class="dish-content">
      <view class="content-section" v-if="dishInfo.cookingSteps">
        <text class="section-title">制作步骤</text>
        <view class="steps-content">
          <text class="steps-text">{{ dishInfo.cookingSteps }}</text>
        </view>
      </view>

      <view class="content-section">
        <text class="section-title">营养成分</text>
        <view class="nutrition-grid">
          <view class="nutrition-item">
            <text class="nutrition-label">热量</text>
            <text class="nutrition-value">{{ dishInfo.calories || 0 }} 千卡</text>
          </view>
          <view class="nutrition-item">
            <text class="nutrition-label">蛋白质</text>
            <text class="nutrition-value">{{ dishInfo.protein || 0 }}g</text>
          </view>
          <view class="nutrition-item">
            <text class="nutrition-label">脂肪</text>
            <text class="nutrition-value">{{ dishInfo.fat || 0 }}g</text>
          </view>
          <view class="nutrition-item">
            <text class="nutrition-label">碳水化合物</text>
            <text class="nutrition-value">{{ dishInfo.carbohydrate || 0 }}g</text>
          </view>
          <view class="nutrition-item">
            <text class="nutrition-label">纤维</text>
            <text class="nutrition-value">{{ dishInfo.fiber || 0 }}g</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 评分弹窗 -->
    <uni-popup ref="ratePopup" type="center">
      <view class="rate-modal">
        <text class="modal-title">为这道菜评分</text>
        <uni-rate v-model="userRating" :size="30" />
        <view class="modal-actions">
          <button class="modal-btn cancel" @click="closeRateModal">取消</button>
          <button class="modal-btn confirm" @click="submitRating">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { getDishDetail, toggleFavorite, rateDish, getUserDishStatus } from '@/api/diet'

export default {
  data() {
    return {
      dishId: '',
      dishInfo: {},
      userRating: 0,
      hasRated: false
    }
  },
  onLoad(options) {
    this.dishId = options.id
    this.loadDishDetail()
  },
  
  onShow() {
    // 页面显示时刷新用户状态
    if (this.dishInfo.id) {
      this.loadUserStatus()
    }
  },
  methods: {
    async loadDishDetail() {
      try {
        const res = await getDishDetail(this.dishId)
        console.log('菜品详情数据:', res)
        const dish = res.data || res || {}
        this.dishInfo = {
          id: dish.dishId,
          name: dish.dishName,
          image: dish.imageUrl ? `http://localhost:8080${dish.imageUrl}` : '/static/images/default-dish.jpg',
          cuisine: dish.cuisine,
          taste: dish.taste,
          cookingMethod: dish.cookingMethod,
          cookingSteps: dish.cookingSteps,
          calories: dish.calories || 0,
          protein: dish.protein || 0,
          fat: dish.fat || 0,
          carbohydrate: dish.carbohydrate || 0,
          fiber: dish.fiber || 0,
          rating: dish.rating || 0,
          favoriteCount: dish.favoriteCount || 0,
          isFavorited: false // 需要从后端获取用户收藏状态
        }
        
        // 立即获取用户状态
        if (this.dishInfo.id) {
          await this.loadUserStatus()
        }
      } catch (error) {
        console.error('加载菜品详情失败:', error)
        this.$modal.msgError('加载失败')
      }
    },
    
    async toggleFavorite() {
      try {
        const result = await toggleFavorite(this.dishId, 100) // 传入用户ID
        this.dishInfo.isFavorited = result.data?.isFavorited || !this.dishInfo.isFavorited
        if (this.dishInfo.isFavorited) {
          this.dishInfo.favoriteCount++
        } else {
          this.dishInfo.favoriteCount--
        }
        this.$modal.msgSuccess(this.dishInfo.isFavorited ? '收藏成功' : '取消收藏')
      } catch (error) {
        this.$modal.msgError('操作失败')
      }
    },
    
    addToNutrition() {
      const selectedDishes = uni.getStorageSync('selectedDishes') || []
      if (!selectedDishes.find(item => item.id === this.dishInfo.id)) {
        selectedDishes.push({
          id: this.dishInfo.id,
          name: this.dishInfo.name,
          image: this.dishInfo.image,
          calories: this.dishInfo.calories,
          protein: this.dishInfo.protein,
          fat: this.dishInfo.fat,
          carbohydrate: this.dishInfo.carbohydrate,
          fiber: this.dishInfo.fiber
        })
        uni.setStorageSync('selectedDishes', selectedDishes)
        this.$modal.msgSuccess('已添加到营养规划')
      } else {
        this.$modal.msgError('该菜品已在规划中')
      }
    },
    
    showRateModal() {
      this.userRating = 0
      this.$refs.ratePopup.open()
    },
    
    closeRateModal() {
      this.$refs.ratePopup.close()
    },
    
    async submitRating() {
      if (this.userRating === 0) {
        this.$modal.msgError('请选择评分')
        return
      }
      
      if (this.hasRated) {
        this.$modal.msgError('您已对该菜品评过分了')
        return
      }
      
      try {
        await rateDish({
          dishId: this.dishInfo.id,
          userId: 100, // 默认用户ID
          rating: this.userRating
        })
        // 更新本地评分显示
        this.hasRated = true
        this.dishInfo.rating = this.userRating
        this.$modal.msgSuccess('评分成功')
        this.closeRateModal()
      } catch (error) {
        this.$modal.msgError('评分失败')
      }
    },
    
    async loadUserStatus() {
      try {
        const userId = 100 // 默认用户ID
        console.log('🔍 开始获取用户状态:', { userId, dishId: this.dishInfo.id })
        
        const res = await getUserDishStatus(userId, [this.dishInfo.id])
        console.log('📥 用户状态API响应:', res)
        
        if (res.code === 200) {
          const { favorites, ratings } = res.data
          console.log('📊 状态数据:', { favorites, ratings })
          
          this.dishInfo.isFavorited = favorites[this.dishInfo.id] || false
          console.log('♥️ 收藏状态:', this.dishInfo.isFavorited)
          
          if (ratings[this.dishInfo.id]) {
            this.userRating = ratings[this.dishInfo.id]
            this.hasRated = true
            console.log('⭐ 评分状态:', this.userRating)
          }
        } else {
          console.log('⚠️ API返回错误:', res)
        }
      } catch (error) {
        console.error('❌ 获取用户状态失败:', error)
      }
    },
    
    async testStatus() {
      console.log('🧪 测试状态点击')
      // 手动设置状态测试
      this.dishInfo.isFavorited = true
      this.userRating = 5
      this.hasRated = true
      
      uni.showToast({
        title: '测试: 已设置为已收藏和5分评分',
        icon: 'none',
        duration: 2000
      })
      
      // 同时调用API获取真实状态
      await this.loadUserStatus()
    }
  }
}
</script>

<style lang="scss" scoped>
.detail-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.dish-header {
  background: white;
  padding: 30rpx;
}

.dish-image {
  width: 100%;
  height: 400rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
}

.dish-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 15rpx;
}

.dish-rating {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
}

.rating-text {
  font-size: 24rpx;
  color: #666;
  margin-left: 15rpx;
}

.dish-tags {
  display: flex;
  flex-wrap: wrap;
}

.tag {
  font-size: 20rpx;
  padding: 6rpx 12rpx;
  border-radius: 10rpx;
  margin-right: 10rpx;
  margin-bottom: 8rpx;
  
  &.cuisine {
    background: #e6f7ff;
    color: #1890ff;
  }
  
  &.taste {
    background: #f6ffed;
    color: #52c41a;
  }
  
  &.method {
    background: #fff2e8;
    color: #fa8c16;
  }
}

.dish-actions {
  background: white;
  padding: 20rpx 30rpx;
  margin-top: 20rpx;
  display: flex;
  justify-content: space-between;
}

.action-btn {
  flex: 1;
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
  border-radius: 35rpx;
  font-size: 26rpx;
  border: 1rpx solid #ddd;
  background: white;
  color: #666;
  margin: 0 10rpx;
  
  &.primary {
    background: #1890ff;
    color: white;
    border-color: #1890ff;
  }
  
  &.favorited {
    background: #ff4d4f;
    color: white;
    border-color: #ff4d4f;
  }
  
  &.rated {
    background: #52c41a;
    color: white;
    border-color: #52c41a;
  }
}

.dish-content {
  margin-top: 20rpx;
}

.content-section {
  background: white;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 20rpx;
}

.ingredients-list {
  display: flex;
  flex-wrap: wrap;
}

.ingredient {
  background: #f0f0f0;
  color: #666;
  font-size: 24rpx;
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
  margin-right: 15rpx;
  margin-bottom: 15rpx;
}

.steps-list {
  
}

.step-item {
  display: flex;
  margin-bottom: 25rpx;
  align-items: flex-start;
}

.step-number {
  width: 50rpx;
  height: 50rpx;
  background: #1890ff;
  color: white;
  border-radius: 50%;
  text-align: center;
  line-height: 50rpx;
  font-size: 24rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.step-content {
  flex: 1;
  font-size: 26rpx;
  color: #333;
  line-height: 1.6;
}

.nutrition-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
}

.nutrition-item {
  background: #f8f9fa;
  padding: 20rpx;
  border-radius: 12rpx;
  text-align: center;
}

.nutrition-label {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.nutrition-value {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.steps-content {
  background: #f8f9fa;
  padding: 20rpx;
  border-radius: 12rpx;
}

.steps-text {
  font-size: 26rpx;
  color: #333;
  line-height: 1.6;
}

.rate-modal {
  background: white;
  border-radius: 20rpx;
  padding: 50rpx;
  text-align: center;
  width: 500rpx;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 40rpx;
}

.modal-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 40rpx;
}

.modal-btn {
  flex: 1;
  height: 70rpx;
  line-height: 70rpx;
  border-radius: 35rpx;
  font-size: 28rpx;
  margin: 0 10rpx;
  
  &.cancel {
    background: #f5f5f5;
    color: #666;
    border: none;
  }
  
  &.confirm {
    background: #1890ff;
    color: white;
    border: none;
  }
}
</style>